import { defineConfig, normalizePath } from 'vite';
import path from 'path';
import vue from '@vitejs/plugin-vue';
import viteEslint from 'vite-plugin-eslint';
import svgLoader from 'vite-svg-loader';
import legacyPlugin from '@vitejs/plugin-legacy';
import autoprefixer from 'autoprefixer';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { visualizer } from 'rollup-plugin-visualizer';
import {
  VantResolver,
  ElementPlusResolver
} from 'unplugin-vue-components/resolvers';

const { resolve } = path;
const variablePath = normalizePath(resolve('./src/styles/variable.scss'));

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const urlSuffix = `${mode}.html`;
  // root: resolve(__dirname, 'src'),
  return {
    base: './',
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [VantResolver(), ElementPlusResolver()]
      }),
      viteEslint(),
      svgLoader(),
      legacyPlugin({
        targets: ['chrome 52'], // 需要兼容的目标列表，可以设置多个
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'] // 面向IE11时需要此插件
      }),
      visualizer({
        open: mode === 'analysis'
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
        '@pc': resolve(__dirname, './src/pages/pc'),
        '@mobile': resolve(__dirname, './src/pages/mobile')
      }
    },
    server: {
      strictPort: false,
      https: false,
      open: `/${urlSuffix}`,
      proxy: {
        '/api': {
          target: '',
          changeOrigin: true,
          rewrite: (path) => path.replace('/^/api', '')
        }
      }
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      assetsInlineLimit: 8 * 1024,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        input: {
          pc: resolve(__dirname, 'pc.html'),
          mobile: resolve(__dirname, 'mobile.html')
        },
        output: {
          // 静态资源分类打包
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            // 静态资源拆分打包
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')
                .toString();
            }
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "${variablePath}"`
        }
      },
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: ['Chrome > 40', 'ff > 31', 'ie 11']
          })
        ]
      }
    }
  };
});
